﻿using System.Collections;
using System.Collections.Generic;
using System.Threading;
using UnityEngine;
using Cysharp.Threading.Tasks;
using System;
using Cysharp.Threading.Tasks.CompilerServices;

//CancellationTokenSource 的CancelAfter 方法
// ***时间后取消任务 可用于做超时处理 
public class Nine : MonoBehaviour
{
    private CancellationTokenSource cts;
    private CancellationToken token;

    private void Start()
    {
        cts = new CancellationTokenSource();

        ClickA();
        //CancellationTokenSouce.CancelAfter是c#提供的原生api 在Unity中不该使用 
        cts.CancelAfter(TimeSpan.FromSeconds(1));
    }

    private async UniTask<int> TestCancelAfter(CancellationToken token)
    {
        for (var i = 0; i < 5; i++)
        {
            Debug.Log($"working...{i + 1}");
            await UniTask.Delay(TimeSpan.FromSeconds(1), cancellationToken: token);
        }

        return 0;
    }

    private async UniTaskVoid ClickA()
    {
        try
        {
            await TestCancelAfter(cts.Token);
            Debug.Log("666");
        }
        catch (OperationCanceledException)
        {
            Debug.Log("a");
        }
    }
}